package com.zsh.servlet;

import com.zsh.util.CookieUtils;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CookieServlet extends BaseServlet {


        protected void testPath(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            Cookie cookie = new Cookie("path1", "path1" );

            //getContextPath() 获取工程路径
            cookie.setPath(request.getContextPath()+ "/abc") ;
            response.addCookie(cookie);
        }

        protected void defaultLife(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            Cookie cookie = new Cookie("defaultLife", "defaultLife");
            cookie.setMaxAge(-1);
            response.addCookie(cookie);
        }

        protected void deleteNow(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            Cookie cookie = CookieUtils.findCookie("key1",request.getCookies());
            cookie.setMaxAge(0);
            response.addCookie(cookie);
        }

        protected void life3600(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            Cookie cookie = new Cookie("life3600", "life3600");
            cookie.setMaxAge(60 * 60);
            response.addCookie(cookie);
        }

        protected void updateCookie(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //方案一：

        Cookie cookie = new Cookie("key1", "newValue1");

        response.addCookie(cookie);

        //方案二：
        Cookie cookie1 = CookieUtils.findCookie("key1",request.getCookies());

        if (cookie1 != null){
            cookie1.setValue("newValue2");
            response.addCookie(cookie1);
        }

    }

        protected void createCookie(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.创建Cookie对象
        Cookie cookie = new Cookie("key1", "value1");
        //2.通知客户端保存
        response.addCookie(cookie);

        response.getWriter().write("Cookie创建成功");
    }

    protected void getCookie(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取Cookie对象
        Cookie[] cookies = request.getCookies();
        //2.通知客户端保存
        for(Cookie cookie: cookies){
            response.getWriter().write(cookie.getName() + "="+ cookie.getValue() + "<br/>");
        }

        //寻找指导cookie
        Cookie iwantCookie = CookieUtils.findCookie("key1",cookies);


    }


}
